package db

import (
	"core/config"
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var (
	DbMaster *gorm.DB
)

func openMySql() {
	db, err := gorm.Open(mysql.Open(config.Config.Dbmaster.Source),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true,
				NoLowerCase:   false,
			},
			Logger:                 NewGormLogger(config.Config.Dbmaster),
			SkipDefaultTransaction: true,
		})
	if err != nil {
		fmt.Println("连接数据库失败, error=" + err.Error())

	} else {
		fmt.Println("打开数据库成功")
	}
	//db.Use(&DbFieldPlugin{})  暂时不需要，update 会重复字段
	DbMaster = db
}

func openSqllite() {
	db, err := gorm.Open(sqlite.Open(config.Config.Dbmaster.Source),
		&gorm.Config{})
	if err != nil {
		fmt.Println("连接数据库失败, error=" + err.Error())

	} else {
		fmt.Println("打开数据库成功")
	}
	//db.Use(&DbFieldPlugin{})  暂时不需要，update 会重复字段
	DbMaster = db
}

func initSql() {
	if config.Config.Dbmaster.Driver == "mysql" {
		openMySql()
	} else if config.Config.Dbmaster.Driver == "sqllite" {
		openSqllite()
	}

}
